package com.dwh.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dwh.model.User;
import com.dwh.msg.Result;
import com.dwh.service.UserService;

@RestController//等同于 @Controller + @ResponseBody
public class UserController {
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/userList", method = RequestMethod.GET)
	public List<User> userList() {
		return userService.findAllUser();
	}
	
	@RequestMapping(value = "findUser/{id}", method = RequestMethod.GET)
	public User findUser(@PathVariable int id){
		return userService.findUserById(id);
	}
	
	@RequestMapping(value = "findUser/{name}", method = RequestMethod.POST)
	public List<User> findUser(@PathVariable String name){
		return userService.findUserByName(name);
	}
	
	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	public User addUser(@RequestParam String name, @RequestParam Integer age) {
		User user = new User();
		user.setName(name);
		user.setAge(age);
		return userService.addUser(user);
	}
	
	@RequestMapping(value = "/addUser/{name}/{age}", method = RequestMethod.POST)
	public User addUser2(@PathVariable String name, @PathVariable Integer age) {
		User user = new User();
		user.setName(name);
		user.setAge(age);
		return userService.addUser(user);
	}
	
	@RequestMapping(value = "/modifyUser", method = RequestMethod.POST)
	public User modifyUser(@RequestParam int id, @RequestParam String name, @RequestParam Integer age) {
		User user = new User();
		user.setId(id);
		user.setName(name);
		user.setAge(age);
		return userService.modifyUser(user);
	}
	
	@RequestMapping(value = "/delUser/{id}", method = RequestMethod.GET)
	public void delUser(@PathVariable int id) {
		userService.delUser(id);
	}
	
	@RequestMapping(value = "/insertUser", method = RequestMethod.POST)
	public User insertUser(@Valid User user, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			System.out.println(bindingResult.getFieldError().getDefaultMessage());
			return null;
		}
		return userService.addUser(user);
	}
	
	@GetMapping("/addOneUser/{age}/{name}")
	public Result<User> addOneUser(User user) throws Exception {
		/*Integer flag = userService.addOneUser(user);
		if (flag == 1) {
			return "你可能还在上小学";
		} else if (flag == 2) {
			return "你可能还在上初中";
		}*/
		return userService.addOneUser(user);
	}
	
	

}
